<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\Order as OrderModel;
use app\common\model\GoodsSpec;
use think\Db;

class AutoCancelOrder extends Command
{
    protected function configure()
    {
        $this->setName('order:auto_cancel')
            ->setDescription('自动取消超时未支付订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始处理超时未支付订单...');
        
        // 查找超过2小时未支付的订单
        $time = time() - 7200; // 当前时间减去2小时
        $orders = OrderModel::with(['items'])
            ->where([
                'status' => 0,  // 未支付状态
                'createtime' => ['<', $time]
            ])->select();
            
        if (empty($orders)) {
            $output->writeln('没有需要处理的订单');
            return;
        }
        
        foreach ($orders as $order) {
            Db::startTrans();
            try {
                // 更新订单状态为已取消
                $order->status = 4;
                $order->save();
                
                // 恢复商品库存
                foreach ($order->items as $item) {
                    $spec = GoodsSpec::where([
                        'id' => $item->spec_id,
                        'goods_id' => $item->goods_id
                    ])->find();
                    
                    if ($spec) {
                        $spec->setInc('stock', $item->quantity);
                        $spec->setDec('sales', $item->quantity);
                    }
                }
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'goods',
                    'title' => '订单已取消',
                    'content' => "您的订单 {$order->order_no} 因超时未支付已自动取消",
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                Db::commit();
                $output->writeln("订单 {$order->order_no} 已取消");
            } catch (\Exception $e) {
                Db::rollback();
                $output->writeln("订单 {$order->order_no} 取消失败：" . $e->getMessage());
            }
        }
        
        $output->writeln('处理完成');
    }
}